import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtGui import QColor


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Toggle Button Example")
        self.setGeometry(100, 100, 300, 200)

        # 创建一个垂直布局
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # 创建一个按钮
        self.toggle_button = QPushButton("On", self)
        self.toggle_button.clicked.connect(self.toggle_button_state)
        self.layout.addWidget(self.toggle_button)
        self.is_on = True  # 初始状态为 On

    def toggle_button_state(self):
        if self.is_on:
            self.toggle_button.setText("Off")
            self.toggle_button.setStyleSheet("color: black;")
            self.is_on = False
        else:
            self.toggle_button.setText("On")
            self.toggle_button.setStyleSheet("color: green;")
            self.is_on = True


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())